import type { InputProps } from 'element-plus'
import { computed, onMounted, reactive, toRef, toRefs } from 'vue'
import { useRouter } from 'vue-router'

import { dictApi, type IDictTypePageItem } from '@/apis'
import {
  type GridExtOptions,
  TABLE_FORMAT,
  TABLE_ITEM_RENDER,
  TABLE_RENDERER,
  useGridExt
} from '@/hooks'
import { dictToOptions, downloadFile, getElementFnFromInstance } from '@/utils'

import type { DictTypeDialogRef } from '../components'

export function useGrid() {
  const state = reactive({
    gridConfig: {
      border: true,
      loading: false,
      showOverflow: true,
      autoResize: true,
      height: 'auto',
      align: 'center',
      resizeConfig: {
        refreshDelay: 10
      },
      toolbarConfig: {
        refresh: true,
        zoom: true,
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      formConfig: {
        items: [
          {
            field: 'dictName',
            title: '字典名称',
            itemRender: {
              name: TABLE_ITEM_RENDER.Input,
              props: {
                placeholder: '请输入'
              } as InputProps
            }
          },
          {
            field: 'dictType',
            title: '字典类型',
            itemRender: {
              name: TABLE_ITEM_RENDER.Input,
              props: {
                placeholder: '请输入'
              } as InputProps
            }
          },
          {
            field: 'status',
            title: '状态',
            itemRender: {
              name: TABLE_ITEM_RENDER.Select,
              props: {
                placeholder: '请选择'
              } as SelectProps
            }
          },
          {
            itemRender: {
              name: TABLE_RENDERER.FormItemBtns
            }
          }
        ]
      },
      columnConfig: {
        minWidth: 220
      },
      columns: [
        { type: 'checkbox', width: 50 },
        {
          field: 'id',
          title: 'ID',
          width: 100
        },
        {
          field: 'dictName',
          title: '字典名称'
        },
        {
          field: 'dictType',
          title: '字典类型',
          slots: {
            default: 'columns_dictType'
          }
        },
        {
          field: 'status',
          title: '状态',
          width: 100,
          slots: {
            default: 'columns_status'
          }
        },
        {
          field: 'remark',
          title: '备注'
        },
        {
          field: 'createTime',
          title: '创建时间',
          formatter: TABLE_FORMAT.Date
        },
        {
          title: '操作',
          width: 100,
          fixed: 'right',
          className: 'columns_operation',
          slots: {
            default: 'columns_operation'
          }
        }
      ],
      pagerConfig: {
        background: true,
        layouts: [
          'PrevJump',
          'PrevPage',
          'JumpNumber',
          'NextPage',
          'NextJump',
          'Sizes',
          'FullJump',
          'Total'
        ],
        pageSize: 15
      },
      proxyConfig: {
        seq: true,
        form: true,
        props: {
          result: 'list',
          total: 'total'
        },
        ajax: {
          query: async ({ page, form }) => {
            const data = await dictApi.getDictTypePage({
              pageSize: page.pageSize,
              pageNum: page.currentPage,
              ...form
            })
            return data
          }
        }
      },
      onCheckboxChange({ checked, row }) {
        checked
          ? state.selectedIds.add(row.id)
          : state.selectedIds.delete(row.id)
      }
    } as GridExtOptions,
    statusOptions: [] as OptionItem[],
    selectedIds: new Set<string>(),
    dictTypeDialogRef: {} as DictTypeDialogRef
  })

  const router = useRouter()
  const gridExtHook = useGridExt(toRef(state, 'gridConfig'))
  const { $msgbox } = getElementFnFromInstance()

  /**
   * 能否导出
   */
  const canExport = computed(() => {
    if (gridExtHook.gridRef.value) {
      return gridExtHook.gridRef.value.getData().length > 0
    }
    return false
  })

  /**
   * 查看字典数据
   */
  function handleViewData(item: any) {
    router.push({
      path: `/system/dictData/${item.id}`
    })
  }

  /**
   * 初始化
   */
  async function init() {
    const [dictStatus] = await Promise.all([
      dictApi.getDictDataList('sys_normal_disable')
    ])

    state.statusOptions = dictToOptions(dictStatus)

    gridExtHook.updateFormItem({
      field: 'status',
      key: 'itemRender.options',
      value: state.statusOptions
    })
  }

  /**
   * 显示新增
   */
  function handleShowAdd() {
    state.dictTypeDialogRef.open()
  }

  /**
   * 显示编辑
   */
  function handleShowEdit(item: IDictTypePageItem) {
    state.dictTypeDialogRef.open(item)
  }

  /**
   * 删除
   */
  function handleDeleteList() {
    $msgbox
      .confirm('确认删除？', '提示', { type: 'warning' })
      .then(async () => {
        await dictApi.deleteDictType({
          ids: Array.from(state.selectedIds)
        })

        handleRefresh()
      })
      .catch(() => {})
  }

  /**
   * 导出
   */
  async function handleExport() {
    const { form, pager } = gridExtHook.gridRef.value.getProxyInfo()!

    try {
      gridExtHook.showLoading()

      const res = await dictApi.exportDictTypePage({
        pageSize: pager.pageSize,
        pageNum: pager.currentPage,
        ...form
      } as any)

      downloadFile(res)
    } finally {
      gridExtHook.hideLoading()
    }
  }

  /**
   * 删除
   */
  function handleDelete(id: string) {
    $msgbox
      .confirm('确认删除？', '提示', { type: 'warning' })
      .then(async () => {
        await dictApi.deleteDictType({
          ids: [id]
        })

        handleRefresh()
      })
      .catch(() => {})
  }

  function handleRefresh() {
    state.selectedIds.clear()
    gridExtHook.refresh()
  }

  onMounted(() => {
    init()
  })

  return {
    ...toRefs(state),
    gridExtHook,
    canExport,
    handleShowAdd,
    handleShowEdit,
    handleDeleteList,
    handleExport,
    handleViewData,
    handleDelete,
    handleRefresh
  }
}
